package org.sction.action.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.sction.action.annotation.Parameter;
import org.sction.action.core.BaseAction;
import org.sction.manager.database.Criterion;
import org.sction.manager.database.CurrentPage;
import org.sction.manager.database.Criterion.CompareType;


/**
 * @author 作者 : sorc
 * @version 创建时间：2012-3-31 下午1:15:25
 * 
 *          类说明
 */
public class JQGridAction extends BaseAction {
	private static final Logger logger = Logger.getLogger(JQGridAction.class);
	@Parameter
	public String id;
	@Parameter
	public String name;
	// 采用的排序方式名称
	@Parameter("sord")
	public String sord = "desc";
	// 用于排序的列名
	@Parameter("sidx")
	public String sidx;
	@Parameter("oper")
	public String oper;
	@Parameter("nd")
	public String nd; // 暂时不清楚啥用的
	// 单条件查询
	@Parameter("searchField")
	public String searchField;
	@Parameter("searchString")
	public String searchString;
	@Parameter("searchOper")
	public String searchOper;
	// 是否请求搜索
	@Parameter("_search")
	public boolean _search;

	// 多属性查询
	@Parameter("filters")
	public String filters;
	// 多条件之间的关系
	protected String groupOp;

	// 行数
	@Parameter("rows")
	public Integer rows = 0;
	// 页码数
	@Parameter("page")
	public Integer page = 0;
	// 数据行总数
	protected Integer record = 0;
	// 页码总数
	protected Integer total = 0;

	public Map<String, Object> refreshGridModel(
			CurrentPage<Map<String, Object>> cpage) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			record = cpage.getTotalRecords();
			resultMap.put("record", record);
			resultMap.put("page", cpage.getPageNum());
			resultMap.put("total", cpage.getTotalPages());
			resultMap.put("gridModel", cpage.getPageItems());
			return resultMap;
		} catch (Exception e) {
			logger.error("refreshGridModel", e);
			return resultMap;
		}
	}

	public Map<String, Object> refreshGridModel(List<?> list) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			record = list.size();
			resultMap.put("record", record);
			resultMap.put("gridModel", list);
			total = 1;
			this.page = 1;
			return resultMap;
		} catch (Exception e) {
			logger.error("refreshGridModel", e);
			return resultMap;
		}
	}

	public Map<String, Object> refreshGridModel(
			CurrentPage<Map<String, Object>> cpage, String... keys) {
		List<Map<String, Object>> dataList = cpage.getPageItems();
		for (int i = 0; i < dataList.size(); i++) {
			Map<String, Object> oldMap = dataList.get(i);
			for (String k : keys) {
				String oldvalue = oldMap.get(k).toString();
				int index = 0;
				String newvalue = ((index = oldvalue.indexOf("\n")) == -1) ? (oldvalue
						.length() > 5 ? oldvalue.substring(0, 5) + "..."
						: oldvalue) : index > 4 ? oldvalue.substring(0, 5)
						+ "..." : oldvalue.substring(0, index) + "...";
				oldMap.put("format" + k, newvalue);
			}
		}
		cpage.setPageItems(dataList);
		return refreshGridModel(cpage);
	}

	public List<Criterion> generateSearchCriteriaFromFilters(String filters) {
		List<Criterion> criteria = new ArrayList<Criterion>();
		if (filters == null || filters.trim().equals("")) {
			criteria.add(this.generateSearchCriterion());
			return criteria;
		}
		// 解析Json
		JSONObject jsonObject = JSONObject.fromObject(filters);
		JSONArray rules = jsonObject.getJSONArray("rules");
		// 设置多条件之间的关系
		this.setGroupOp((String) jsonObject.get("groupOp"));
		for (Object obj : rules) {
			JSONObject rule = (JSONObject) obj;
			String field = rule.getString("field");
			String op = rule.getString("op");
			String data = rule.getString("data");
			// 生成Criterion
			Criterion criterion = this.generateSearchCriterion(field, data, op);

			// 将多条件的Criterion加入Lst(多属性)
			if (criterion != null) {
				criteria.add(criterion);
			}
		}
		return criteria;
	}

	public Criterion generateSearchCriterion(String searchField,
			String searchString, String searchOper) {
		Criterion criterion = null;
		// 如果searchField、searchString、searchOper均不为null，且searchString不为空字符串时，则创建Criterion
		if (searchField != null && searchString != null
				&& !searchString.trim().equals("") && searchOper != null) {
			if ("eq".equals(searchOper)) {
				criterion = Criterion.getEqualCriterion(searchField,
						searchString, null);
			} else if ("ne".equals(searchOper)) {
				criterion = Criterion.getCompareCriterion(CompareType.NE,
						searchField, searchString, null);
			} else if ("lt".equals(searchOper)) {
				criterion = Criterion.getCompareCriterion(CompareType.LT,
						searchField, searchString, null);
			} else if ("le".equals(searchOper)) {
				criterion = Criterion.getCompareCriterion(CompareType.LTE,
						searchField, searchString, null);
			} else if ("gt".equals(searchOper)) {
				criterion = Criterion.getCompareCriterion(CompareType.GT,
						searchField, searchString, null);
			} else if ("ge".equals(searchOper)) {
				criterion = Criterion.getCompareCriterion(CompareType.GTE,
						searchField, searchString, null);
			} else if ("bw".equals(searchOper)) {
				criterion = Criterion.getLikeCriterion(searchField,
						searchString + "%", null);
			} else if ("bn".equals(searchOper)) {
				criterion = Criterion.getNotLikeCriterion(searchField,
						searchString + "%", null);
			} else if ("ew".equals(searchOper)) {
				criterion = Criterion.getLikeCriterion(searchField, "%"
						+ searchString, null);
			} else if ("en".equals(searchOper)) {
				criterion = Criterion.getNotLikeCriterion(searchField, "%"
						+ searchString, null);
			} else if ("cn".equals(searchOper)) {
				criterion = Criterion.getLikeCriterion(searchField, "%"
						+ searchString + "%", null);
			} else if ("nc".equals(searchOper)) {
				criterion = Criterion.getNotLikeCriterion(searchField, "%"
						+ searchString + "%", null);
			}
		}
		return criterion;

	}

	public Criterion generateSearchCriterion() {
		return this.generateSearchCriterion(searchField, searchString,
				searchOper);
	}

	public Map<?, ?> getParameterSimpleMap() {
		Iterator<?> kit = parameterMap.keySet().iterator();
		Map<String, Object> param = new HashMap<String, Object>();
		while (kit.hasNext()) {
			String key = String.valueOf(kit.next());
			String v[] = (String[]) null;
			try {
				v = (String[]) parameterMap.get(key);
			} catch (Exception e) {
				continue;
			}
			if (v != null && v.length == 1)
				param.put(key, v[0]);
			else
				param.put(key, v);
		}
		return param;
	}

	public String getOrderStr() {
		if (this.sidx != null && !this.sidx.trim().equals("")) {
			return (" order by " + this.sidx + " " + this.sord + " ");
		} else {
			return "";
		}
	}

	public String getOrderStr(String od) {
		if (this.sidx != null && !this.sidx.trim().equals("")) {
			return (" order by " + od + " " + this.sidx + " " + this.sord + " ");
		} else {
			return " order by " + od;
		}
	}

	public String getGroupOp() {
		return groupOp;
	}

	public void setGroupOp(String groupOp) {
		this.groupOp = groupOp;
	}

	public Integer getRows() {
		return rows;
	}

	public void setRows(Integer rows) {
		this.rows = rows;
	}

	public Integer getPage() {
		return page;
	}

	public void setPage(Integer page) {
		this.page = page;
	}

	public boolean getSearch() {
		return _search;
	}

	public void setSearch(boolean _search) {
		this._search = _search;
	}

	public String getFilters() {
		return filters;
	}

	public void setFilters(String filters) {
		this.filters = filters;
	}

}
